package com.hansheng.action.tailing;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hansheng.service.impl.SemiProductServiceImpl;
import com.hansheng.util.JsonHelper;
import com.hansheng.util.PrintWriterHelper;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.TreeSet;

/**
 * Created by GoldenMan on 2017/5/16.
 */
public class GetSemiProductAction extends ActionSupport implements ServletResponseAware, ServletRequestAware {
    private HttpServletResponse httpServletResponse;
    private HttpServletRequest httpServletRequest;
    private String outFormNo;
    private SemiProductServiceImpl semiProductService;

    public void setSemiProductService(SemiProductServiceImpl semiProductService) {
        this.semiProductService = semiProductService;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.httpServletRequest = request;
    }

    public String getOutFormNo() {
        return outFormNo;
    }

    public void setOutFormNo(String outFormNo) {
        this.outFormNo = outFormNo;
    }

    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.httpServletResponse = response;
        httpServletResponse.setContentType("text/html;charset=utf-8");
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
    }

    @Override
    public String execute() throws Exception {
        JSONArray semiProductArray = semiProductService.getSemiProductArray(getOutFormNo());
        JSONObject returnJson = JsonHelper.successJSONBuilder(semiProductArray);
        returnJson.put("sidSet", getSidSet(semiProductArray).toArray());
        PrintWriterHelper.send(returnJson);
        return null;
    }

    private TreeSet getSidSet(JSONArray jsonArray) {
        TreeSet set = new TreeSet();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            set.add(jsonObject.get("sid"));
        }
        return set;
    }
}